package com.kpmg.datalake.autopackage.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.kpmg.datalake.autopackage.dao.VersionManagerMapper;
import com.kpmg.datalake.autopackage.model.VersionManager;
import com.kpmg.datalake.autopackage.service.VersionManagementService;
import com.kpmg.datalake.autopackage.vo.VersionManagerDTO;
import com.kpmg.datalake.common.vo.ServerResponse;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * @Author: Richard.ji [richard.ji@kpmg.com]
 * @Date: 2018-07-13 10:36:37
 * @Description: 版本管理
 */
@Service
public class VersionManagementServiceImpl implements VersionManagementService {

    @Resource
    private VersionManagerMapper versionManagerMapper;

    private static final String MESSAGE = "获取版本信息成功";

    /**
     * 获取版本信息
     * @return
     */
    @Override
    public ServerResponse getVersionInfoList() {
        VersionManager versionManager = versionManagerMapper.getVersionInfoList();

        return ServerResponse.createBySuccess(MESSAGE, versionManager);
    }

    @Override
    public ServerResponse getVersionInfoListById(String versionId) {
        VersionManager versionManager = versionManagerMapper.getVersionInfoListById(versionId);

        return ServerResponse.createBySuccess(MESSAGE, versionManager);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ServerResponse insertVersion(VersionManagerDTO versionManagerDTO) {
        LocalDateTime now = LocalDateTime.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String dateStr = formatter.format(now);

        VersionManager versionManager = new VersionManager();
        BeanUtils.copyProperties(versionManagerDTO, versionManager);

        versionManager.setVersionNo("VBA_PKG_" + dateStr + "_V" + 1.0);
        versionManager.setDelInd(new BigDecimal(0));
        int versionCode = versionManagerMapper.insertSelective(versionManager);

        return ServerResponse.createBySuccess("保存版本信息成功", versionCode);
    }

	@Override
	public ServerResponse getVersionInfoListBySearch(VersionManagerDTO versionManager) {
        PageHelper.startPage(versionManager.getPageIndex(), versionManager.getPageSize());

	    List<VersionManager> versionManagerList = versionManagerMapper.getVersionInfoListBySearch(versionManager.getFileName());

        PageInfo<VersionManager> requestPageList = new PageInfo<>(versionManagerList);

        return ServerResponse.createBySuccess(MESSAGE, requestPageList);
	}
}
